package com.jumi.microservice.common;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.exception.ExceptionSupply;
import com.jumi.microservice.common.file.FileUploadUtils;
import com.jumi.microservice.common.file.FileUtils;
import com.jumi.microservice.framework.ServerConfig;
import com.jumi.microservice.framework.SupplyConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ssk
 * @create 2020/8/1 17:42
 **/
@RestController
@Api(tags = {"【通用配置】通用类接口"})
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Resource
    private ServerConfig serverConfig;


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    @ApiOperation("通用下载接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名"),
            @ApiImplicitParam(name = "delete", value = "下载后是否删除源文件(true/false)", dataType = "Boolean"),
    })
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {

        if (!FileUtils.isValidFilename(fileName)) {
            throw new ExceptionSupply(500, StringUtils.format("文件名称({})非法，不允许下载。 ", fileName)).newException();
        }
        String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
        String filePath = SupplyConfig.getDownloadPath() + fileName;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));

            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            throw new ExceptionSupply(500, "文件流生成失败!").newException();
        }
        if (delete) {
            FileUtils.deleteFile(filePath);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public ResponseResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = SupplyConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map data = new HashMap();
            data.put("fileName", fileName);
            data.put("url", url);
            return ResponseResult.success(data);
        } catch (Exception e) {
            return ResponseResult.error(e.getMessage());
        }
    }

}
